package com.task.manage.system.controller;

import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

import com.task.manage.common.core.domain.entity.SysUser;
import com.task.manage.common.utils.ShiroUtils;
import com.task.manage.common.utils.StringUtils;
import com.task.manage.system.domain.TaskManage;
import com.task.manage.system.service.*;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.task.manage.common.annotation.Log;
import com.task.manage.common.enums.BusinessType;
import com.task.manage.system.domain.PersonnelData;
import com.task.manage.common.core.controller.BaseController;
import com.task.manage.common.core.domain.AjaxResult;
import com.task.manage.common.utils.poi.ExcelUtil;
import com.task.manage.common.core.page.TableDataInfo;

import javax.annotation.Resource;

/**
 * 人员信息Controller
 *
 * @author ruoyi
 * @date 2024-05-10
 */
@Controller
@RequestMapping("/system/data")
public class PersonnelDataController extends BaseController {
    private String prefix = "system/data";

    @Autowired
    private IPersonnelDataService personnelDataService;

    @Autowired
    private ISysUserService sysUserService;

    @Resource
    private RequireTaskService requireTaskService;

    @Resource
    private ISysRoleService roleService;


    @RequiresPermissions("system:data:view")
    @GetMapping()
    public String data() {
        return prefix + "/data";
    }

    /**
     * 查询人员信息列表
     */
    @RequiresPermissions("system:data:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(PersonnelData personnelData) {
        startPage();
        SysUser user = ShiroUtils.getSysUser();
        if(!user.isAdmin()){
            Set<String> roles = roleService.selectRoleKeys(user.getUserId());
            boolean hasCommon = roles.stream().anyMatch(role -> role.equals("common"));
            if(!hasCommon){
                personnelData.setUserId(user.getUserId());
                personnelData.setQueryAllFlag("Y");
            }
        }
        List<PersonnelData> list = personnelDataService.selectPersonnelDataList(personnelData);
        return getDataTable(list);
    }

    /**
     * 查询人员信息列表
     */
    @RequiresPermissions("system:data:list")
    @PostMapping("/requireList")
    @ResponseBody
    public TableDataInfo requireList(PersonnelData personnelData) {
        startPage();
        SysUser user = ShiroUtils.getSysUser();
        if(!user.isAdmin()){
            Set<String> roles = roleService.selectRoleKeys(user.getUserId());
            boolean hasCommon = roles.stream().anyMatch(role -> role.equals("common"));
            if(!hasCommon){
                personnelData.setUserId(user.getUserId());
                personnelData.setQueryAllFlag("Y");
            }
        }
        List<PersonnelData> list = personnelDataService.selectPersonnelDataStatusList(personnelData);
        return getDataTable(list);
    }

    /**
     * 导出人员信息列表
     */
    @RequiresPermissions("system:data:export")
    @Log(title = "人员信息", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(PersonnelData personnelData) {
        List<PersonnelData> list = personnelDataService.selectPersonnelDataList(personnelData);
        ExcelUtil<PersonnelData> util = new ExcelUtil<PersonnelData>(PersonnelData.class);
        return util.exportExcel(list, "人员信息数据");
    }

    /**
     * 新增人员信息
     */
    @GetMapping("/add")
    public String add(ModelMap mmap) {
        //这里只查询角色为客服人员的员工
        SysUser user = ShiroUtils.getSysUser();
        boolean queryFlag=false;
        if(!user.isAdmin()){
            Set<String> roles = roleService.selectRoleKeys(user.getUserId());
            boolean hasCommon = roles.stream().anyMatch(role -> role.equals("common"));
            if(!hasCommon){
                queryFlag=true;
            }
        }
        List<SysUser> userList = sysUserService.selectUserisCustomer();
        if(queryFlag){
           Long userId=user.getUserId();
           userList=userList.stream().filter(a -> a.getUserId().equals(userId)).collect(Collectors.toList());
        }
        mmap.put("userList", userList);
        return prefix + "/add";
    }

    /**
     * 新增保存人员信息
     */
    @RequiresPermissions("system:data:add")
    @Log(title = "人员信息", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(PersonnelData personnelData) {
        personnelData.setStatus(0);
        return toAjax(personnelDataService.insertPersonnelData(personnelData));
    }

    /**
     * 修改人员信息
     */
    @RequiresPermissions("system:data:edit")
    @GetMapping("/edit/{id}")
    public String edit(@PathVariable("id") Long id, ModelMap mmap) {
        PersonnelData personnelData = personnelDataService.selectPersonnelDataById(id);
        //这里只查询角色为客服人员的员工
        SysUser user = ShiroUtils.getSysUser();
        boolean queryFlag=false;
        if(!user.isAdmin()){
            Set<String> roles = roleService.selectRoleKeys(user.getUserId());
            boolean hasCommon = roles.stream().anyMatch(role -> role.equals("common"));
            if(!hasCommon){
                queryFlag=true;
            }
        }
        List<SysUser> userList = sysUserService.selectUserisCustomer();
        if(queryFlag){
            Long userId=user.getUserId();
            userList=userList.stream().filter(a -> a.getUserId().equals(userId)).collect(Collectors.toList());
        }
        mmap.put("userList", userList);
        mmap.put("personnelData", personnelData);
        return prefix + "/edit";
    }

    /**
     * 批量设置人员任务数量初始化页面
     * @return
     */
    @RequiresPermissions("system:data:batch")
    @GetMapping("/setUpUrl/{ids}")
    public String setUpUrl(@PathVariable("ids") String ids,ModelMap mmap){
        logger.info("量设置人员任务数量初始化页面获取到的参数id:{}",ids);
        mmap.put("ids",ids);
        return prefix + "/setUpurl";
    };


    @RequiresPermissions("system:data:batch")
    @GetMapping("/setUpTaskCounts/{ids}/{taskLimit}")
    @ResponseBody
    public AjaxResult setUpTaskCounts(@PathVariable("ids") String ids,@PathVariable("taskLimit") Integer taskLimit,ModelMap mmap){
        logger.info("获取到的参数id:{}",ids);
        List<Long> idsList = Arrays.stream(ids.split(","))
                .map(Long::parseLong)
                .collect(Collectors.toList());
        personnelDataService.updateBatchTaskLimit(idsList,taskLimit);
        return AjaxResult.success();
    };

    /**
     * 修改保存人员信息
     */
    @RequiresPermissions("system:data:edit")
    @Log(title = "人员信息", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(PersonnelData personnelData) {
        return toAjax(personnelDataService.updatePersonnelData(personnelData));
    }

    /**
     * 删除人员信息
     */
    @RequiresPermissions("system:data:remove")
    @Log(title = "人员信息", businessType = BusinessType.DELETE)
    @PostMapping("/remove")
    @ResponseBody
    public AjaxResult remove(String ids) {
        return toAjax(personnelDataService.deletePersonnelDataByIds(ids));
    }

    /**
     * 客户随机获取任务
     */
    @RequiresPermissions("require:task")
    @PostMapping("/require")
    @ResponseBody
    public AjaxResult require(String ids) {
        if (StringUtils.isEmpty(ids)) {
            return error("请选择对应的人员信息");
        }
        logger.info("获取到的id是:{}", ids);
       List<Long> idsList = Arrays.stream(ids.split(","))
                .map(Long::parseLong)
                .collect(Collectors.toList());
        List<PersonnelData> personnelDataList = personnelDataService.selectBactchList(idsList);
        StringBuffer resBuffer=new StringBuffer();
        for(PersonnelData personnelData:personnelDataList){
            TaskManage taskManage = new TaskManage();
            taskManage.setPersonId(personnelData.getId());
            //以下是获取任务逻辑
            try {
                StringBuffer resp= requireTaskService.requirePersonTask(personnelData);
                resBuffer.append(resp);
            }catch (Exception e){
                logger.error("任务派发失败,继续下一个任务personId:{},e",personnelData.getId(),e);
            }
        }
        String msg=resBuffer.toString();
        if(msg.contains("已达")||msg.contains("没有")){
            return AjaxResult.warn(resBuffer.toString());
        }else{
            return success(resBuffer.toString());
        }
    };

    /**
     * 用户状态修改
     */
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @RequiresPermissions("system:user:edit")
    @PostMapping("/changeStatus")
    @ResponseBody
    public AjaxResult changeStatus(PersonnelData personnelData) {
        personnelDataService.updatePersonnelData(personnelData);
        return AjaxResult.success();
    }
}
